import os
from flask import Flask, render_template, request, redirect, url_for, send_file, flash, session
from database import *
from database import insert_firmware, remove_firmware, insert_brand
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'
app.config['UPLOAD_FOLDER'] = 'static/firmwares'
app.config['ALLOWED_EXTENSIONS'] = {'bin', 'hex', 'img'}

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@app.route('/')
def index():
    brands = get_brands()
    brands_count, firmwares_count, uploaders_count = get_stats()

    brand_data = []
    for brand in brands:
        firmwares = get_firmwares_by_brand(brand['id'])
        latest_version = get_brand_latest_version(brand['id'])
        brand_data.append({
            'id': brand['id'],
            'name': brand['name'],
            'latest_version': latest_version,
            'firmwares': firmwares
        })

    return render_template(
        'index.html',
        brands_count=brands_count,
        firmwares_count=firmwares_count,
        uploaders_count=uploaders_count,
        brands=brand_data
    )


@app.route('/add_firmware', methods=['POST'])
def add_firmware():
    brand_id = request.form.get('brand')
    version = request.form.get('version')
    uploader = request.form.get('uploader')
    changelog = request.form.get('changelog')
    firmware_file = request.files['firmware_file']
    timestamp = request.form.get('timestamp')

    # 验证输入
    if not all([brand_id, version, uploader, changelog, firmware_file, timestamp]):
        flash('所有字段都必须填写', 'danger')
        return redirect(url_for('index'))

    # 检查文件类型
    if not allowed_file(firmware_file.filename):
        flash('不允许的文件类型', 'danger')
        return redirect(url_for('index'))

    # 获取品牌名称
    brands = get_brands()
    brand_name = None
    for brand in brands:
        if str(brand['id']) == brand_id:
            brand_name = brand['name']
            break

    if not brand_name:
        flash('无效的品牌', 'danger')
        return redirect(url_for('index'))

    # 创建品牌目录
    brand_dir = os.path.join(app.config['UPLOAD_FOLDER'], brand_name)
    os.makedirs(brand_dir, exist_ok=True)

    # 保存固件文件
    filename = f"{version}_{datetime.now().strftime('%Y%m%d%H%M%S')}.{firmware_file.filename.rsplit('.', 1)[1].lower()}"
    file_path = os.path.join(brand_dir, filename)
    firmware_file.save(file_path)

    # 保存到数据库
    insert_firmware(brand_id, version, uploader, changelog, file_path, timestamp)

    flash('固件添加成功', 'success')
    return redirect(url_for('index'))


@app.route('/download/<int:firmware_id>')
def download_firmware(firmware_id):
    file_path = get_firmware_path(firmware_id)
    if file_path and os.path.exists(file_path):
        return send_file(file_path, as_attachment=True)

    flash('找不到固件文件', 'danger')
    return redirect(url_for('index'))


@app.route('/delete/<int:firmware_id>', methods=['POST'])
def delete_firmware(firmware_id):
    file_path = remove_firmware(firmware_id)
    if file_path and os.path.exists(file_path):
        os.remove(file_path)
        flash('固件删除成功', 'success')
    else:
        flash('找不到固件', 'danger')

    return redirect(url_for('index'))


@app.route('/view_changelog/<int:firmware_id>')
def view_changelog(firmware_id):
    conn = get_db_connection()
    firmware = conn.execute('SELECT changelog FROM firmwares WHERE id = ?', (firmware_id,)).fetchone()
    conn.close()

    if firmware:
        return firmware['changelog']

    return "无更新日志"


@app.route('/add_brand', methods=['POST'])
def add_brand():
    brand_name = request.form.get('brand_name')

    if not brand_name:
        flash('品牌名称不能为空', 'danger')
        return redirect(url_for('index'))

    # 检查品牌是否已存在
    existing_brands = get_brands()
    if any(brand['name'] == brand_name for brand in existing_brands):
        flash('品牌已存在', 'warning')
        return redirect(url_for('index'))

    # 添加品牌到数据库
    insert_brand(brand_name)
    flash('品牌添加成功', 'success')
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(debug=True)